package com.atguigu.flink0922.chapter05.transform;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/2 14:32
 */
public class Flink01_Map_Rich {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);
        
//        final DataStreamSource<Integer> s1 = env.fromElements(1, 2, 3, 4);
        final DataStreamSource<String> s1 = env.socketTextStream("hadoop162", 9999);
        
        s1
            .map(new RichMapFunction<String, String>() {
                
               // 每个并行度只执行一次
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 做一些初始化的工作: 连接外部存储, 初始化一些参数等等
                    System.out.println("open ...");
                }
    
    
                @Override
                public String map(String value) throws Exception {
                    return value + ">>";
                }
    
                // 关闭时执行, 每个并行度执行一次
                @Override
                public void close() throws Exception {
                    // 关闭资源
                    System.out.println("close ...");
                }
    
            })
            .print("平方");
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
